/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/DB/SqlDelayThread.h"

#include <cstdint>
#include <mysql.h>
#include "Shared/DB/SqlOperation.h"
#pragma warning(disable:4355)

#define SQLTHREAD_SLEEPTIME  10


namespace Shared {
namespace DB {

    SqlDelayThread::SqlDelayThread(Database* db, SqlConnection* conn) 
        : _sqlQueue()
        , _db(db)
        , _conn(conn)
        , _running(true)
        , _thread(this)
    {
    }

    SqlDelayThread::~SqlDelayThread(void)
    {
        processRequests();
    }

    void SqlDelayThread::run(void)
    {
        mysql_thread_init();

        while (_running)
        {
            Thread::sleep(SQLTHREAD_SLEEPTIME);
            processRequests();
        }

        mysql_thread_end();
    }

    bool SqlDelayThread::start(void)
    {
        return _thread.start();
    }

    void SqlDelayThread::stop(void)
    {
        _running = false;
        _thread.join();
    }

    void SqlDelayThread::processRequests(void)
    {
        SqlOperation* s = NULL;
        while (_sqlQueue.next(s))
        {
            s->execute(_conn);
            delete s;
        }
    }

}}